package com.winhxd.b2c.customer.controller;

import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.AdminUserStoreIdConstant;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.CopyPageConfigCondition;
import com.winhxd.b2c.common.domain.customer.condition.CustomerPageConfigCondition;
import com.winhxd.b2c.common.domain.customer.condition.QueryPageConfigCondition;
import com.winhxd.b2c.common.domain.customer.model.CustomerPageConfig;
import com.winhxd.b2c.common.domain.customer.vo.CustomerPageConfigVO;
import com.winhxd.b2c.common.domain.system.user.enums.UserLevelEnum;
import com.winhxd.b2c.common.domain.system.user.model.SysUser;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.customer.PageConfigServiceClient;
import com.winhxd.b2c.common.feign.system.UserServiceClient;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.service.CustomerStoreInfoSerivce;
import com.winhxd.b2c.customer.service.PageConfigService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @program: hxd-outlet-parent
 * @description: 后台页面配置实现类
 * @author: ChenYanqi
 * @create: 2019-01-11 18:09
 **/
@Api(value = "api - PageConfig", tags = "pageConfig-controller")
@RestController
public class PageConfigServiceController implements PageConfigServiceClient {

    private Logger logger = LoggerFactory.getLogger(PageConfigServiceController.class);

    @Autowired
    PageConfigService pageConfigService;

    @Autowired
    CustomerStoreInfoSerivce customerStoreInfoSerivce;

    @Autowired
    UserServiceClient userServiceClient;

    @Autowired
    Cache cache;

    private static final int PAGE_CONFIG_ONE_DAY_MILLS = 24 * 60 * 60 * 1000;

    @Override
    public ResponseResult<Boolean> savePageConfig(@RequestBody CustomerPageConfigCondition condition) {
        Integer level = condition.getLevel();
        Long storeId = 0L;
        if (UserLevelEnum.YUANYI.getLevelCode() == level) {
            storeId = AdminUserStoreIdConstant.ADMIN_USER_STORE_ID;
            condition.setOutletPage(true);
        } else {
            Long sysUserId = condition.getCreatedBy();
            storeId = getStoreIdBySysUserId(sysUserId);
            condition.setOutletPage(false);
        }
        condition.setHomePage(false);
        condition.setReleaseStatus(false);
        CustomerPageConfig storePageConfig = new CustomerPageConfig();
        BeanUtils.copyProperties(condition, storePageConfig);
        storePageConfig.setStoreId(storeId);
        storePageConfig.setCreated(new Date());
        storePageConfig.setCreatedBy(condition.getCreatedBy());
        Boolean flag = pageConfigService.savePageConfig(storePageConfig);
        ResponseResult<Boolean> result = new ResponseResult<>();
        result.setData(flag);
        return result;
    }

    @Override
    public ResponseResult<Boolean> modifyPageConfig(@RequestBody CustomerPageConfigCondition condition) {
        Long userId = condition.getCreatedBy();
        Integer level = condition.getLevel();
        Long storeId = 0L;
        if (UserLevelEnum.YUANYI.getLevelCode() == level) {
            storeId = AdminUserStoreIdConstant.ADMIN_USER_STORE_ID;
        } else {
            Long sysUserId = userId;
            storeId = getStoreIdBySysUserId(sysUserId);

        }

        Boolean homePage = condition.getHomePage();
        String pageTitle = condition.getPageTitle();
        String pageDetail = condition.getPageDetail();
        CustomerPageConfig storePageConfig = new CustomerPageConfig();
        BeanUtils.copyProperties(condition, storePageConfig);
        storePageConfig.setStoreId(storeId);
        storePageConfig.setUpdated(new Date());
        storePageConfig.setUpdatedBy(userId);
        Boolean flag = pageConfigService.modifyPageConfig(storePageConfig);
        if (homePage) {
            CustomerPageConfigVO customerPageConfigVO = new CustomerPageConfigVO();
            customerPageConfigVO.setPageTitle(pageTitle);
            customerPageConfigVO.setPageDetail(pageDetail);
            cache.hset(CacheName.HOME_PAGE_CONFIGURATION, storeId + "", JsonUtil.toJSONString(customerPageConfigVO));
            cache.expire(CacheName.HOME_PAGE_CONFIGURATION, Integer.valueOf(DurationFormatUtils.formatDuration(PAGE_CONFIG_ONE_DAY_MILLS, "s")));
        }
        ResponseResult<Boolean> result = new ResponseResult<>();
        result.setData(flag);
        return result;
    }

    @Override
    public ResponseResult<Boolean> deletePageConfig(@RequestBody QueryPageConfigCondition condition) {
        Long id = condition.getId();
        Long storeId = condition.getSysUserId();
        Boolean homePage = condition.getHomePage();
        if (homePage) {
            logger.warn("删除自定义页面时，该页面为首页,门店id -{}，页面id -{}", storeId, id);
            throw new BusinessException(BusinessCode.CODE_108201);
        }
        Boolean flag = pageConfigService.deletePageConfig(id);
        ResponseResult<Boolean> result = new ResponseResult<>();
        result.setData(flag);
        return result;
    }

    @Override
    public ResponseResult<PagedList<CustomerPageConfig>> queryPageConfig(@RequestBody QueryPageConfigCondition condition) {
        Integer level = condition.getLevel();
        PagedList<CustomerPageConfig> customerPageConfigs = null;
        Long storeId;
        if (UserLevelEnum.YUANYI.getLevelCode() == level) {
            storeId = AdminUserStoreIdConstant.ADMIN_USER_STORE_ID;
            condition.setStoreId(storeId);
            customerPageConfigs = pageConfigService.selectByStoreId(condition, false);
        } else {
            Long sysUserId = condition.getSysUserId();
            storeId = getStoreIdBySysUserId(sysUserId);
            condition.setStoreId(storeId);
            customerPageConfigs = pageConfigService.selectByStoreId(condition, true);
            CustomerPageConfig pageConfig = pageConfigService.selectHomePageByStoreId(storeId);
            if (!ObjectUtils.isEmpty(pageConfig)) {
                customerPageConfigs.getData().forEach(storePageConfig -> {
                    if (storePageConfig.getOutletPage()) {
                        storePageConfig.setHomePage(false);
                    }
                });
            }
        }
        customerPageConfigs.getData().forEach(customerPageConfig -> {
            customerPageConfig.setLevel(level);
        });
        ResponseResult<PagedList<CustomerPageConfig>> result = new ResponseResult<>();
        result.setData(customerPageConfigs);
        return result;
    }

    @Override
    public ResponseResult<Boolean> releasePageConfig(@RequestBody QueryPageConfigCondition condition) {
        CustomerPageConfig customerPageConfig = new CustomerPageConfig();
        customerPageConfig.setId(condition.getId());
        customerPageConfig.setReleaseStatus(true);
        customerPageConfig.setUpdated(new Date());
        customerPageConfig.setUpdatedBy(condition.getSysUserId());
        Boolean flag = pageConfigService.releasePageConfig(customerPageConfig);
        ResponseResult<Boolean> result = new ResponseResult<>();
        result.setData(flag);
        return result;
    }

    @Override
    public ResponseResult<Boolean> setHomePage(@RequestBody QueryPageConfigCondition condition) {
        Long userId = condition.getSysUserId();
        Long storeId = condition.getStoreId();
        Long id = condition.getId();
        Boolean releaseStatus = condition.getReleaseStatus();
        if (!releaseStatus) {
            logger.warn("设置主页时，该页面未发布,用户id -{}，页面id -{}", userId, id);
            throw new BusinessException(BusinessCode.CODE_108501);
        }
        CustomerPageConfig pageConfig = new CustomerPageConfig();
        pageConfig.setId(id);
        pageConfig.setStoreId(storeId);

        Boolean flag = false;
        if (AdminUserStoreIdConstant.ADMIN_USER_STORE_ID.longValue() == storeId.longValue() &&
                UserLevelEnum.YUANYI.getLevelCode() != condition.getLevel()) {
            Long loginStoreId = getStoreIdBySysUserId(userId);
            storeId = loginStoreId;
            pageConfig.setStoreId(loginStoreId);
            flag = pageConfigService.updateHomePage(pageConfig);
        } else {
            pageConfig.setHomePage(true);
            pageConfig.setUpdated(new Date());
            pageConfig.setUpdatedBy(userId);
            flag = pageConfigService.setHomePage(pageConfig);
        }

        if (flag) {
            CustomerPageConfig customerPageConfig = pageConfigService.selectPageConfigById(id);
            CustomerPageConfigVO customerPageConfigVO = new CustomerPageConfigVO();
            customerPageConfigVO.setPageTitle(customerPageConfig.getPageTitle());
            customerPageConfigVO.setPageDetail(customerPageConfig.getPageDetail());
            cache.hset(CacheName.HOME_PAGE_CONFIGURATION, storeId + "", JsonUtil.toJSONString(customerPageConfigVO));
            cache.expire(CacheName.HOME_PAGE_CONFIGURATION, Integer.valueOf(DurationFormatUtils.formatDuration(PAGE_CONFIG_ONE_DAY_MILLS, "s")));
        }
        ResponseResult<Boolean> result = new ResponseResult<>();
        result.setData(flag);
        return result;
    }

    @Override
    public ResponseResult<Boolean> copyPageConfig(@RequestBody CopyPageConfigCondition condition) {
        Long id = condition.getId();
        CustomerPageConfig customerPageConfig = pageConfigService.selectPageConfigById(id);
        Integer level = condition.getLevel();
        if (UserLevelEnum.YUANYI.getLevelCode() == level) {
            customerPageConfig.setStoreId(AdminUserStoreIdConstant.ADMIN_USER_STORE_ID);
            customerPageConfig.setOutletPage(true);
        } else {
            Long sysUserId = condition.getSysUserId();
            Long storeId = getStoreIdBySysUserId(sysUserId);
            customerPageConfig.setStoreId(storeId);
            customerPageConfig.setOutletPage(false);
        }
        customerPageConfig.setId(null);
        customerPageConfig.setPageTitle(condition.getPageTitle());
        customerPageConfig.setHomePage(false);
        customerPageConfig.setReleaseStatus(false);
        customerPageConfig.setCreated(new Date());
        customerPageConfig.setCreatedBy(condition.getSysUserId());
        customerPageConfig.setUpdated(null);
        customerPageConfig.setUpdatedBy(null);
        Boolean flag = pageConfigService.savePageConfig(customerPageConfig);
        ResponseResult<Boolean> result = new ResponseResult<>();
        result.setData(flag);
        return result;
    }

    @Override
    public ResponseResult<CustomerPageConfig> getPageConfigById(@RequestParam("id") Long id) {
        CustomerPageConfig customerPageConfig = pageConfigService.selectPageConfigById(id);
        ResponseResult<CustomerPageConfig> result = new ResponseResult<>();
        result.setData(customerPageConfig);
        return result;
    }


    /**
     * 后台通过customerId获取storeid(获取sys_user 表里的 parent_id)
     */
    private Long getStoreIdBySysUserId(Long id) {
        ResponseResult<SysUser> result = userServiceClient.getSysUserById(id);
        Long storeId = result.getDataWithException().getCustomerId();
        return storeId;
    }


}
